<template>
  <div v-loading="loading" element-loading-text="拼命加载中..." class="app-container">
    <el-page-header  class="box-shadow mb-3" icon="arrow-left" @back="handleGoBack">
      <template #content>
        <span>发起进件</span>
      </template>
      <template #extra>
        <div class="flex items-center">
          <el-button icon="arrow-left" @click="handleGoBack">返回上页</el-button>
        </div>
      </template>
    </el-page-header>

    <div class="app-container-main">
      <el-row :gutter="12">
        <el-col :md="12">
          <el-card class="content-card">
            <el-form ref="formRef" :disabled="readonly" :model="formData" :rules="formRules"
                  label-width="120"  >
              <el-form-item label="选择通道：">
                <el-select v-model="types" :disabled="readonly" placeholder="请选择" filterable>
                  <el-option label="直付通收款" :value="0">
                  </el-option>
                </el-select>
<!--                <el-input v-model="formData.name" :readonly="readonly" placeholder="请选择" />-->
              </el-form-item>
              <el-form-item label="签约支付宝号：" prop="alipay_logon_id">
                <el-input v-model="formData.alipay_logon_id" :readonly="readonly" placeholder="请输入签约支付宝号" />
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

      </el-row>
      <el-row :gutter="12">
        <el-col :md="24">
          <div class="el-descriptions__header">
            <div class="el-descriptions__title">产品信息</div>
          </div>
          <el-card class="content-card">
            <div class="mb-4">
              <el-checkbox-group v-model="type" size="large" @change="handleChange" :disabled="readonly">
                <div class="mb-3">
                  <el-checkbox label="小程序支付场景" value="tiny_app" border />
                  <el-checkbox label="H5场景" value="wap" border />
                  <el-checkbox label="线下当面付场景" value="offline" border />
                </div>
                <div class="mb-4">
                  <el-checkbox label="APP支付场景" value="app" border />
                  <el-checkbox label="网站支付场景" value="pc" border />
                  <el-checkbox label="JSAPI" value="jsapi" border />
                </div>
              </el-checkbox-group>
            </div>
            <el-form ref="formRateRef" :disabled="readonly" :model="info" label-width="140px">

              <div v-for="(item, index) in info.payee" :key="index">
                <div class="el-descriptions__header">
                  <div class="el-descriptions__title">{{ item.type}}费率设置</div>
                </div>
                <el-form-item :label="'费率(%)：'" :prop="'payee.' + index + '.rate'"
                              :rules="getValidationRules(index)">
                  <el-input v-model="item.rate" :readonly="readonly" placeholder="请设置费率" />
                </el-form-item>
                <el-form-item :label="'单笔最小金额：'" :prop="'payee.' + index + '.min_amount'"
                              :rules="getValidationRules(index)">
                  <el-input v-model="item.min_amount" :readonly="readonly" placeholder="请输入单笔最小金额" />
                </el-form-item>
                <el-form-item :label="'单笔最大金额：'" :prop="'payee.' + index + '.max_amount'"
                              :rules="getValidationRules(index)">
                  <el-input v-model="item.max_amount" :readonly="readonly" placeholder="请输入单笔最大金额" />
                </el-form-item>
                <el-form-item :label="'单日限额：'" :prop="'payee.' + index + '.limit_amount'"
                              :rules="getValidationRules(index)">
                  <el-input v-model="item.limit_amount" :readonly="readonly" placeholder="请输入单日限额" />
                </el-form-item>
                <el-form-item :label="'单笔手续费：'" :prop="'payee.' + index + '.extra_charge'"
                              :rules="getValidationRules(index)">
                  <el-input v-model="item.extra_charge" :readonly="readonly" placeholder="请输入单笔手续费" />
                </el-form-item>
                <el-form-item :label="'单笔最少手续费：'" :prop="'payee.' + index + '.min_charge'"
                              :rules="getValidationRules(index)">
                  <el-input v-model="item.min_charge" :readonly="readonly" placeholder="请输入单笔最少手续费" />
                </el-form-item>
                <el-form-item :label="'结算方式：'" :prop="'payee.' + index + '.settle_mode'"
                              :rules="getValidationRules(index)">
                  <el-select v-model="item.settle_mode" :disabled="readonly" placeholder="请选择" filterable>
                    <el-option label="T1" value="T1"> </el-option>
                    <el-option label="D1" value="D1"> </el-option>
                    <el-option label="D0" value="D0"> </el-option>
                  </el-select>
                </el-form-item>
                <div class="el-descriptions__header" v-if="item.type!='offline'">
                  <div class="el-descriptions__title">{{ item.type}}补充信息</div>
                </div>
                <template v-if="item.type=='tiny_app'">
                  <el-form-item :label="'支付宝小程序名称：'" :prop="'payee.' + index + '.site_name'"
                                :rules="getValidationRules(index)">
                    <el-input v-model="item.site_name" :readonly="readonly" placeholder="请输入支付宝小程序名称" />
                  </el-form-item>
                  <el-form-item :label="'支付宝小程序id：'" :prop="'payee.' + index + '.tiny_app_id'"
                                :rules="getValidationRules(index)">
                    <el-input v-model="item.tiny_app_id" :readonly="readonly" placeholder="请输入支付宝小程序id" />
                  </el-form-item>
                </template>
                <template v-if="item.type=='wap'">
                  <el-form-item :label="'WAP站点名称：'" :prop="'payee.' + index + '.site_name'"
                                :rules="getValidationRules(index)">
                    <el-input v-model="item.site_name" :readonly="readonly" placeholder="请输入WAP站点名称" />
                  </el-form-item>
                  <el-form-item :label="'WAP站点链接：'" :prop="'payee.' + index + '.site_url'"
                                :rules="getValidationRules(index)">
                    <el-input v-model="item.site_url" :readonly="readonly" placeholder="请输入WAP站点链接" />
                  </el-form-item>
                  <el-form-item :label="'补充图片：'" :prop="'payee.' + index + '.screenshot_image'"
                                :rules="getValidationRules(index)">
                    <UploadImage v-model="item.screenshot_image" :disabled="readonly" :show-delete="true" :show-tip="false"/>
                  </el-form-item>
                </template>
                <template v-if="item.type=='app'">
                  <el-form-item :label="'APP站点名称：'" :prop="'payee.' + index + '.site_name'"
                                :rules="getValidationRules(index)">
                    <el-input v-model="item.site_name" :readonly="readonly" placeholder="请输入APP站点名称" />
                  </el-form-item>
                  <el-form-item :label="'补充图片：'" :prop="'payee.' + index + '.site_url'"
                                :rules="getValidationRules(index)">
                    <UploadImage v-model="item.screenshot_image" :disabled="readonly" :show-delete="true" :show-tip="false"/>
                  </el-form-item>
                </template>
                <template v-if="item.type=='pc'">
                  <el-form-item :label="'PC站点名称：'" :prop="'payee.' + index + '.site_name'"
                                :rules="getValidationRules(index)">
                    <el-input v-model="item.site_name" :readonly="readonly" placeholder="请输入pc站点名称" />
                  </el-form-item>
                  <el-form-item :label="'PC站点链接：'" :prop="'payee.' + index + '.site_url'"
                                :rules="getValidationRules(index)">
                    <el-input v-model="item.site_url" :readonly="readonly" placeholder="请输入PC站点链接" />
                  </el-form-item>
                  <el-form-item :label="'补充图片：'" :prop="'payee.' + index + '.site_url'"
                                :rules="getValidationRules(index)">
                    <UploadImage v-model="item.screenshot_image" :disabled="readonly" :show-delete="true" :show-tip="false"/>
                  </el-form-item>
                </template>
                <template v-if="item.type=='jsapi'">
                  <el-form-item :label="'支付宝小程序名称：'" :prop="'payee.' + index + '.site_name'"
                                :rules="getValidationRules(index)">
                    <el-input v-model="item.site_name" :readonly="readonly" placeholder="请输入支付宝小程序名称" />
                  </el-form-item>
                  <el-form-item :label="'支付宝小程序链接：'" :prop="'payee.' + index + '.site_url'"
                                :rules="getValidationRules(index)">
                    <el-input v-model="item.site_url" :readonly="readonly" placeholder="请输入支付宝小程序链接" />
                  </el-form-item>
                </template>
                <el-divider />
              </div>

            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="app-container-main">
      <div style="float: right;">
        <el-button @click="handleGoBack" round>取消</el-button>
        <el-button type="primary" round @click="onSubmitForm" v-if="mode!='query'">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted , watch} from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { MANAGERAdd, MANAGERDetail ,MANAGERUpdate} from '@/api/api-manager';
import { useRoute, useRouter } from 'vue-router';
import { useTabsNavStore } from '@/store';
import {UploadImage} from "@/components/upload";
import {merchantEntry, merchantEntryDetail, merchantEntryInfo, merchantEntryUpdate} from "@/api/api-store.ts";
const tabsNavStore = useTabsNavStore();
const currentRoute = useRoute();
const router = useRouter();
defineOptions({name: 'entry-info'});
// Props
const props = defineProps({

});
const readonly=ref(false)
const route = useRoute();
// Reactive references
const id = ref<Number>(0);
const loading = ref(false);
const type = ref<string[]>([]);
const types=ref(0)
const formData = ref({ alipay_logon_id: '',mid:0 });
const info = ref<Object>({}); // Adjust type as necessary
const formRef = ref<FormInstance>();
const formRateRef = ref<FormInstance>();
const status = ref<Number>(1)
const initData = async (id: number) => {
  loading.value = false;
  formData.value.mid=id
  readonly.value = mode.value == 'query';
  if(mode.value=='edit' || mode.value=='query'){
    loading.value=true
    await merchantEntryDetail({action:'info',id:ids.value}).then(res => {
      loading.value=false
      formData.value.alipay_logon_id=res.body.info.alipay_logon_id
      type.value=res.body.product.map(item => item.type)
      const payee = res.body.product.map(item => ({
        type: item.type,
        rate: item.info.rate,
        min_amount: item.info.min_amount,
        max_amount: item.info.max_amount,
        min_charge: item.info.min_charge,
        settle_mode: '', // 默认值
        extra_charge: item.info.extra_charge,
        limit_amount: item.info.limit_amount,
        site_name: item.support.site_name,
        site_url: item.support.site_url,
        screenshot_image: item.support.screenshot_image,
        tiny_app_id: item.support.tiny_app_id
      }));
      info.value.payee=payee;
    }).catch(err=>{
      loading.value=false
    })
  }
}

// Form rules
const formRules = reactive<FormRules>({
  alipay_logon_id: [{ required: true, message: '小程序支付宝号不能为空', trigger: 'blur' }],
});

// Validation rules for payee info
const getValidationRules = (index: number) => {
  return [
    { required: true, message: '不能为空', trigger: 'blur' }
  ];
};

// Handle change in checkbox group
const handleChange = () => {
  // 记录当前选中的类型
  const selectedTypes = new Set(type.value);
  // 确保 payee 是一个数组，然后更新 payee 列表，只保留选中的类型
  if (!info.value.payee) {
    info.value.payee = []; // 确保 payee 是一个数组
  }

  info.value.payee = info.value.payee.filter(item => selectedTypes.has(item.type));

  // 为新选中的类型添加条目
  type.value.forEach(selectedType => {
    // 检查当前类型是否已在 payee 中
    const exists = info.value.payee.some(item => item.type === selectedType);
    if (!exists) {
      info.value.payee.push({
        type: selectedType,
        rate: '',
        min_amount: '',
        max_amount: '',
        min_charge: '',
        settle_mode:'',
        extra_charge: '',
        limit_amount:'',
        site_name:'',
        site_url:'',
        screenshot_image:'',
        tiny_app_id:''
      });
    }
  });
};

// Handle form submission
//提交
const onSubmitForm = async () => {
  try {
    const v1 = await formRef.value?.validate();
    const v2 = await formRateRef.value?.validate();
    console.log('验证结果:', v1, v2); // 调试验证结果
    if (type.value.length <= 0) {
      ElMessage({ type: 'error', message: '请选择设置费率类型' });
      return
    }
    let payee = info.value.payee.map(item => ({
      type: item.type,
      info: {
        rate: item.rate,
        min_amount: item.min_amount,
        max_amount: item.max_amount,
        min_charge: item.min_charge,
        settle_mode:item.settle_mode,
        extra_charge: item.extra_charge,
        limit_amount:item.limit_amount
      },
      support:{
        site_url:item.site_url,
        site_name:item.site_name,
        screenshot_image:item.screenshot_image,
        tiny_app_id:item.tiny_app_id
      }
    }));
    let data = {
      ...formData.value,
      product:payee,
    }
    if(mode.value=='edit'){
      // data = { ...data, id: ids.value };
      merchantEntryUpdate(data, { action: 'update' }).then(res => {
        ElMessage({ type: 'success', message: "编辑成功"});
        mode.value='edit'
        initData(id.value);
      })
    }else{
      merchantEntry(data, { action: 'add' }).then(res => {
        ElMessage({ type: 'success', message: "成功"});
        mode.value='edit'
        initData(id.value);

        // handleGoBack()
      })
    }

  } catch (error) {
    console.log('校验错误:', error); // 打印校验错误
    ElMessage({ type: 'error', message: '请检查是否有必填项未完善' });
  }
};
const handleGoBack = async(refresh = false) => {
  await tabsNavStore.delView(currentRoute);
  let params = {refresh: refresh ? 1 : 0}
  // await router.push({path: '/store/list', state: {params}});
  router.go(-1)
  await handleReset()
}
const handleReset = async () => {
  info.value = {}
  formData.value = { mid: 0, alipay_logon_id: '' }
  status.value = 1
}
const mode=ref()
const ids=ref()
// Load initial data
onMounted(async () => {
  // await handleReset();
  console.log(route.params)
  id.value=Number(route.params.id)
  ids.value=Number(route.query.id)
  mode.value=route.query.mode
  await initData(id.value);
});
</script>

<style lang="scss" scoped>
.app-container-main {
  .el-form-item {
    margin-bottom: 16px !important;
  }

  :deep(.el-form-item__content) {
    max-width: 36rem;
  }

  .el-input-number {
    max-width: 10rem;
  }

  .el-descriptions__title {
    border-left: 3px solid var(--el-color-primary);
    padding-left: 10px;
    font-weight: 500;
    font-size: 14px;
    line-height: 16px;
  }
}
</style>
